package com.knowswift.issues.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Slf4j
public class MessageCallback implements MqttCallback {
    private MqttClient client;
    private final MqttMessageHandlerContext messageHandlerContext;

    public MessageCallback(MqttClient client, MqttMessageHandlerContext messageHandlerContext) {
        this.client = client;
        this.messageHandlerContext = messageHandlerContext;
    }

    @Override
    public void connectionLost(Throwable cause) {
        log.error(cause.getMessage(), cause);
        while (true) {
            try {
                if (!client.isConnected()) {
                    client.reconnect();
                    if (client.isConnected()) {
                        log.info("mqtt reconnect successfully.");
                        return;
                    } else {
                        log.error("mqtt reconnect failed.");
                        TimeUnit.SECONDS.sleep(30);
                    }
                }
            } catch (Exception e) {
                log.error("reconnect failed.", e);
            }
        }
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) {
        log.info(topic);
        log.info(Arrays.toString(message.getPayload()));
        messageHandlerContext.handle(topic, message);

    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {

        log.info("发送到topic({})成功", Arrays.toString(token.getTopics()));

    }
}
